<template>
  <el-button type="primary" style="margin-left: 16px" @click="drawer = true">
    open
  </el-button>

  <el-drawer v-model="drawer" title="角色权限规则" :with-header="false">
    <span>角色权限规则</span>
    <el-form
      ref="ruleFormRef"
      :model="ruleForm"
      :rules="rules"
      label-width="120px"
      class="demo-ruleForm"
      :size="formSize"
      status-icon
    >
      <el-form-item label="角色名称" prop="roleName">
        <el-input v-model="ruleForm.roleName" placeholder="请填写角色名称" />
      </el-form-item>
      <el-form-item label="角色权限" prop="permission">
        <el-tree
          :data="MainRoutes"
          :props="defaultProps"
          show-checkbox
          @check="handleCheck"
          node-key="path"
        />
      </el-form-item>
      <el-form-item label="是否开启" prop="open">
        <el-switch
          v-model="open"
          class="ml-2"
          style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm(ruleFormRef)">
          创建
        </el-button>
        <el-button @click="resetForm(ruleFormRef)">重置</el-button>
      </el-form-item>
    </el-form>
  </el-drawer>
</template>

<script lang="ts" setup>
import { reactive, ref } from "vue";
import { FormInstance, FormRules, ElMessage } from "element-plus";
import { MainRoutes } from "../../../router/index";
import { rolePost } from "../../../api/role";
const drawer = ref(false);
const open = ref(true);

interface RuleForm {
  roleName: string;
  permission: Array<any>;
  open: boolean;
}

const formSize = ref("default");
const ruleFormRef = ref<FormInstance>();
const ruleForm = reactive<RuleForm>({
  roleName: "",
  permission: [],
  open: true,
});

const rules = reactive<FormRules<RuleForm>>({
  roleName: [{ required: true, message: "请填写角色", trigger: "blur" }],
  permission: [{ required: true, message: "请勾选权限", trigger: "blur" }],
});

const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            console.log(ruleForm);
            rolePost(ruleForm).then(() => {
                ElMessage({
                    showClose: true,
                    message: '创建成功',
                    type: 'success',
                })
            })
        } else {
            console.log('error submit!', fields)
        }
    })
}

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
  // console.log(router);
};
// 角色权限
const defaultProps = {
    label: (item:any) => item.meta.label
}


const handleCheck = (a: any, { checkedKeys }: any) => {
  console.log("checkedKeys", checkedKeys, a);
  ruleForm.permission = checkedKeys;
};
</script>